package cn.qianxun.meta.common.log.event;

import cn.qianxun.meta.common.core.utils.BeanCopyUtils;
import cn.qianxun.meta.log.api.dto.ChangeFieldValueLog;
import cn.qianxun.meta.log.api.dto.SaveSafeValueLog;
import cn.qianxun.meta.log.api.dto.SysLoginLog;
import cn.qianxun.meta.log.api.dto.SysOperLog;
import cn.qianxun.meta.log.api.feign.ISysLogProvider;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 异步调用日志服务
 *
 * @author fuzhilin
 */
@Component
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class LogEventListener {


    private final ISysLogProvider sysLogProvider;

    /**
     * 保存系统日志记录
     */
    @Async
    @EventListener
    public void saveLog(OperLogEvent operLogEvent) {
        SysOperLog SysOperLog = BeanCopyUtils.copy(operLogEvent, SysOperLog.class);
        sysLogProvider.saveLog(SysOperLog);
    }

    @Async
    @EventListener
    public void saveLoginLog(LogininforEvent logininforEvent) {
        SysLoginLog sysLoginLog = BeanCopyUtils.copy(logininforEvent, SysLoginLog.class);
        sysLogProvider.saveLoginLog(sysLoginLog);
    }

    @Async
    @EventListener
    public void saveChangeFieldLog(ChangeFieldValueLogEvent changeFieldValueLogEvent) {
        List<ChangeFieldValueLog> list = changeFieldValueLogEvent.getFieldValueList().stream().map(fieldValue -> {
            ChangeFieldValueLog fieldValueVO = new ChangeFieldValueLog();
            BeanCopyUtils.copy(fieldValue, fieldValueVO);
            return fieldValueVO;
        }).collect(Collectors.toList());
        sysLogProvider.saveChangeFieldLog(list);
    }

    @Async
    @EventListener
    public void saveSafeValueLog(SafeValueLogEvent safeValueLogEvent) {
        List<SaveSafeValueLog> list = safeValueLogEvent.getSafeValueLogList().stream().map(safeValueVO -> {
            SaveSafeValueLog safeValueLog = new SaveSafeValueLog();
            BeanCopyUtils.copy(safeValueVO, safeValueLog);
            return safeValueLog;
        }).collect(Collectors.toList());
        sysLogProvider.saveSafeValueLog(list);
    }

}
